package inits

import (
	"api-server/basic/config"
	__ "api-server/proto"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"

	"log"
)

func init() {
	InitClient()
	InitConfig()
	InitMysql()
	InitRedis()
}

func InitConfig() {
	viper.SetConfigFile("C:\\Users\\14306\\Desktop\\likeShop\\shop-server\\dev.yaml")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Println("配置文件读取失败")
	}
	if err := viper.Unmarshal(&config.ApiClient); err != nil {
		fmt.Println("配置文件解析失败")
	}
	log.Println("viper is success")
}

func InitClient() {
	conn, err := grpc.NewClient("127.0.0.1:8888", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	config.ShopClient = __.NewShopClient(conn)
}
func InitMysql() {
	var err error
	//add := config.GlobalConfig.Nacos
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := "root:root@tcp(127.0.0.1:3306)/shop?charset=utf8mb4&parseTime=True&loc=Local"
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	log.Println("mysql is succoss")
}

func InitRedis() {
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     config.ApiClient.Redis.Addr,
		Password: config.ApiClient.Redis.Password, // no password set
		DB:       config.ApiClient.Redis.DB,       // use default DB
	})
	log.Println("redis is success")
}
